using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERPBackend.Data;
using ERPBackend.Models;
using Microsoft.EntityFrameworkCore;
using BCrypt.Net;

namespace ERPBackend.Services
{
    public class UserService : IUserService
    {
        private readonly ApplicationDbContext _context;

        public UserService(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task<IEnumerable<User>> GetAllUsersAsync()
        {
            return await _context.Users
                .ToListAsync() ?? Enumerable.Empty<User>();
        }

        public async Task<User?> GetUserByIdAsync(int userId)
        {
            return await _context.Users
                .FirstOrDefaultAsync(u => u.Id == userId);
        }

        public async Task<User> CreateUserAsync(User user)
        {
            // 加密密码
            user.Password = BCrypt.Net.BCrypt.HashPassword(user.Password);

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return user;
        }

        public async Task<User?> UpdateUserAsync(User user)
        {
            var existingUser = await _context.Users.FindAsync(user.Id);
            if (existingUser == null)
            {
                return null;
            }

            // 更新用户信息
            existingUser.Username = user.Username;
            existingUser.Gender = user.Gender;
            existingUser.DepartmentId = user.DepartmentId;
            existingUser.Position = user.Position;
            existingUser.Phone = user.Phone;
            existingUser.Email = user.Email;
            existingUser.HireDate = user.HireDate;
            existingUser.Status = user.Status;
            existingUser.UpdatedBy = user.UpdatedBy;
            existingUser.UpdatedTime = DateTime.Now;

            // 如果密码不为空，则更新密码
            if (!string.IsNullOrEmpty(user.Password))
            {
                existingUser.Password = BCrypt.Net.BCrypt.HashPassword(user.Password);
            }

            await _context.SaveChangesAsync();

            return existingUser;
        }

        public async Task<bool> DeleteUserAsync(int userId)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null)
            {
                return false;
            }

            // 删除用户角色关联
            var userRoles = await _context.UserRoles.Where(ur => ur.UserId == userId).ToListAsync();
            _context.UserRoles.RemoveRange(userRoles);

            // 删除用户
            _context.Users.Remove(user);
            await _context.SaveChangesAsync();

            return true;
        }

        public async Task<IEnumerable<User>> SearchUsersAsync(string keyword)
        {
            // 不使用导航属性
            var users = await _context.Users
                .Where(u => u.Username.Contains(keyword))
                .ToListAsync();
            return users ?? Enumerable.Empty<User>();
        }

        public async Task<bool> ChangeUserStatusAsync(int userId, bool status)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null)
            {
                return false;
            }

            user.Status = status;
            user.UpdatedTime = DateTime.Now;
            await _context.SaveChangesAsync();

            return true;
        }

        public async Task<bool> ResetPasswordAsync(int userId, string newPassword)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null)
            {
                return false;
            }

            user.Password = BCrypt.Net.BCrypt.HashPassword(newPassword);
            user.UpdatedTime = DateTime.Now;
            await _context.SaveChangesAsync();

            return true;
        }
    }
}